# -*- coding: utf-8 -*-
# @Date   : 2020/3/23
# @File   : R23_IC_EnforcementRecordCheck_2D_CF1.py
# @Author : zhaochen
'''eof
name:申请人强制执行金额校验
code:R23_IC_EnforcementRecordCheck_2D_CF1
tableName:
columnName:
groups:个人征信校验
dependencies:IC_DSJ_2D
type:常用指标
datasourceType:在线指标
description:
eof'''

import sys
import pandas as pd
import datetime
reload(sys)
sys.setdefaultencoding('utf-8')

null_type_list = ['', ' ', None, 'null', 'Null', 'NULL', '/', '-', '--']

last_year_list = [(datetime.datetime.now() - pd.tseries.offsets.DateOffset(years=i)).strftime('%Y-%m-%d')\
                    for i in range(6)]


def getTable(data, tableName, occurTimes):
    '''
        获取表信息
        :param data:表上层的字典对象
        :param tableName:表的名字
        :param occurTimes:表出现的次数，如果是0代表此表可以不出现，如果是1代表此表必须出现
        :return:该表全部数据
        '''
    table = data.get(tableName)
    if occurTimes == 0:
        if table is None:
            return [{}]
        elif table == "":
            return ""
        elif isinstance(table, list) is False or len(table) == 0:
            return None
        else:
            return data.get(tableName)
    if occurTimes == 1:
        if table == "":
            return ""
        elif table is None or isinstance(table, list) is False or len(table) == 0:
            return None
        else:
            return data.get(tableName)


def isfloat(x):
    '''
    判断x为float类型且大于等于0
    :param x:
    :return:
    '''
    try:
        if isinstance(float(x), float) and float(x) >= 0:
            if str(x) in ['inf', 'infinity', 'INF', 'INFINITY', 'True']:
                return False
            else:
                return True
        else:
            return False
    except:
        return False


def Formate(time):
    import re
    import datetime
    r = re.compile(r'\D+')
    try:
        date = datetime.datetime.strptime(time, '%Y.%m.%d').strftime('%Y-%m-%d')
    except:
        try:
            date = datetime.datetime.strptime(time, '%Y-%m-%d').strftime('%Y-%m-%d')
        except:
            try:
                date = datetime.datetime.strptime(time, '%Y/%m/%d').strftime('%Y-%m-%d')
            except:
                try:
                    tmp = r.sub('', time)
                    date = datetime.datetime.strptime(tmp, '%Y%m%d').strftime('%Y-%m-%d')
                except:
                    date = None
    return date


def R23_IC_EnforcementRecordCheck_2D_CF1():
    data = IC_DSJ_2D['data']
    # 强制执行记录
    PCE = getTable(data, 'PCE', 1)
    if PCE is None:
        return u'缺失值'
    elif PCE == "":
        return 0
    else:
        # 强制执行记录信息单元
        PF03 = getTable(PCE[0], 'PF03', 0)
        if PF03 is None or PF03 == "":
            return u"缺失值"
        elif PF03 == [{}]:
            return 0
        else:
            result = set()
            for i in PF03:
                try:
                    # 强制执行记录信息段
                    PF03A = getTable(i, 'PF03A', 1)
                    if PF03A is None or PF03A == "":
                        result.add(None)
                    else:
                        # 立案日期(PF03AR01)
                        PF03AR01 = PF03A[0].get('PF03AR01')
                        # 申请执行标的金额
                        PF03AJ01 = PF03A[0].get('PF03AJ01')
                        # 已执行标的金额(PF03AJ02)
                        PF03AJ02 = PF03A[0].get('PF03AJ02')
                        if PF03AR01 == '0000-00':
                            if (isfloat(PF03AJ01) is False and isfloat(PF03AJ02) is False):
                                result.add(None)
                            else:
                                money = (float(PF03AJ01) if isfloat(PF03AJ01) else float(PF03AJ02))
                                date = PF03AR01
                                result.add((date, money))

                        if Formate(PF03AR01) is None or (isfloat(PF03AJ01) is False and isfloat(PF03AJ02) is False):
                            result.add(None)
                        else:
                            money = (float(PF03AJ01) if isfloat(PF03AJ01) else float(PF03AJ02))
                            date = PF03AR01
                            result.add((date, money))

                except:
                    result.add(None)
                    continue
            if None in result and len(result) == 1:
                return u'缺失值'
            else:
                result = list(filter(lambda x:x is not None, list(result)))
                res = 0
                for item in result:
                    if isfloat(item[1]):
                        res += float(item[1])
                return res

result = R23_IC_EnforcementRecordCheck_2D_CF1()